package com.xindacloud.sms.adapter.service.sms.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.xindacloud.sms.adapter.bo.Countries;
import com.xindacloud.sms.adapter.bo.Networks;
import com.xindacloud.sms.adapter.bo.PricingBO;
import com.xindacloud.sms.adapter.entity.SmsAgent;
import com.xindacloud.sms.adapter.entity.SmsPricing;
import com.xindacloud.sms.adapter.exception.ServiceException;
import com.xindacloud.sms.adapter.service.business.ISmsAgentService;
import com.xindacloud.sms.adapter.service.business.ISmsPricingService;
import com.xindacloud.sms.adapter.service.sms.ISyncPricingService;
import com.xindacloud.sms.adapter.utils.Base64DecodeHelp;
import com.xindacloud.sms.adapter.utils.UnionResultHelp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Deprecated
@Service("nexmoSyncPricing")
@Slf4j
public class NexmoSyncPricingServiceImpl implements ISyncPricingService {


    private final ISmsAgentService smsAgentService;

    private final RestTemplate restTemplate;

    @Autowired
    ISmsPricingService pricingService;

    @Autowired
    public NexmoSyncPricingServiceImpl(ISmsAgentService smsAgentService, RestTemplate restTemplate) {
        this.smsAgentService = smsAgentService;
        this.restTemplate = restTemplate;
    }


    @Override
    public Boolean syncPricing(String agentId) {

        SmsAgent smsAgent = smsAgentService.queryAgentById(agentId);
        Optional.ofNullable(smsAgent)
                .orElseThrow(() -> new ServiceException("平台资源不存在", UnionResultHelp.StatusEnum.NotFound.code()));

        List<SmsPricing> smsPricingList = new ArrayList<>();

        String url = "https://rest.nexmo.com/account/get-full-pricing/outbound/sms?api_key=" + Base64DecodeHelp.decode(smsAgent.getApiKey()) + "&api_secret=" + Base64DecodeHelp.decode(smsAgent.getApiSecret()) + "";
        ResponseEntity<PricingBO> mapResponseEntity = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<PricingBO>() {
        });

        PricingBO pricingBO = mapResponseEntity.getBody();
        if (Objects.isNull(pricingBO)) {
            return false;
        }
        if (CollectionUtils.isEmpty(pricingBO.getCountries())) {
            log.warn("Nexmo平台返回运营商价格列表Countries为空.");
            return false;
        }
        for (Countries crs : pricingBO.getCountries()) {
            if (CollectionUtils.isEmpty(crs.getNetworks())) {
                log.warn("CountryCode: {},CountryName:{}Nexmo平台返回运营商价格列表Networks为空.",
                        crs.getCountryCode(), crs.getCountryName());
                continue;
            }
            for (Networks nrs : crs.getNetworks()) {
                SmsPricing smsPricing = SmsPricing.builder()
                        .agentId(agentId)
                        .countryCode(crs.getCountryCode())
                        .countryName(crs.getCountryName())
                        .countryDisplayName(crs.getCountryDisplayName())
                        .currency(crs.getCurrency())
                        .prefix(crs.getDialingPrefix())
                        .defaultPrice(BigDecimal.valueOf(Double.valueOf(crs.getDefaultPrice())))
                        .costPrice(BigDecimal.valueOf(Double.valueOf(nrs.getPrice())))
                        .networkCode(nrs.getNetworkCode())
                        .networkAliases(CollectionUtils.isNotEmpty(nrs.getAliases()) ? String.join(",", nrs.getAliases()) : "")
                        .networkName(nrs.getNetworkName())
                        .price(BigDecimal.valueOf(Double.valueOf(nrs.getPrice())))
                        .type(nrs.getType())
                        .mcc(nrs.getMcc())
                        .mnc(nrs.getMnc())
                        .build();
                smsPricingList.add(smsPricing);

            }
        }

        if (CollectionUtils.isNotEmpty(pricingService.querySmsPricingListByAgentId(agentId))) {
            pricingService.deleteSmsPricingListByAgentId(agentId);
        }
        return pricingService.saveBatchPricing(smsPricingList);
    }
}

